<?php

namespace App\Store\Services\Order;

use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\Account;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Basic\TemplateQuality;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Order\OrderSales as ModelsOrderOrderSales;
use App\Store\Models\Sysset\Commission\Changegoods;
use App\Store\Models\Sysset\Commission\Discount;
use App\Store\Models\Sysset\Commission\Preferention;
use App\Store\Models\Sysset\Commission\Priceandfee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OrderSales
{

    /**
     * 销售开单计算业绩和提成
     */
    public static function computePerformanceAndCommission(array $goodslist_new, array $recoverygoodslist_new, array $goods_moeny, array $recoverygoods_moeny)
    {
        if (count($recoverygoodslist_new) <= 0) {
            foreach ($goodslist_new as &$gv) {
                $gv['performance'] = $gv['real_total_money'];
                // 是素金必然是克算
                if ($gv['is_sujin'] == 1 && $gv['is_gram'] = 1) { //素金

                    $gv['commission1_price_d'] = 0;
                    $gv['commission2_price_d'] = 0;
                    $gv['commission1_cost_price_d'] = 0;
                    $gv['commission2_cost_price_d'] = 0;
                    $gv['commission1_cost_price'] = 0;
                    $gv['commission2_cost_price'] = 0;


                    // 金价优惠
                    $glodprice_total = $gv['glod_price_discount'] ?? -1;
                    //工费优惠
                    $fee_total = $gv['cost_price_discount'] ?? -1;

                    $preferential_total = $glodprice_total + $fee_total;

                    $ruleinfo = Priceandfee::where([
                        ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']],
                        ['preferential_min', '<=', $preferential_total], ['preferential_max', '>=', $preferential_total],
                        ['glodprice_min', '<=', $glodprice_total], ['glodprice_max', '>=', $glodprice_total],
                        ['fee_min', '<=', $fee_total], ['fee_max', '>=', $fee_total], ['is_del', 1]
                    ])->first();

                    if (!empty($ruleinfo)) {
                        if ((int)$ruleinfo['is_method'] == 1) {
                            $gv['commission1_cost_price'] = intval($ruleinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_cost_price'] = intval($ruleinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_cost_price'] = intval($ruleinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_cost_price'] = intval($ruleinfo['commission_money_2'] * $gv['weight']);
                        }
                    }


                    $glodpriceinfo = Preferention::where([['type', 1], ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['preferential_min', '<=', $glodprice_total], ['preferential_max', '>=', $glodprice_total], ['is_del', 1]])->first();
                    if (!empty($glodpriceinfo)) {
                        if ((int)$glodpriceinfo['is_method'] == 1) {
                            $gv['commission1_price_d'] = intval($glodpriceinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_price_d'] = intval($glodpriceinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_price_d'] = intval($glodpriceinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_price_d'] = intval($glodpriceinfo['commission_money_2'] * $gv['weight']);
                        }

                    }

                    $feeinfo = Preferention::where([['type', 2], ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['preferential_min', '<=', $fee_total], ['preferential_max', '>=', $fee_total], ['is_del', 1]])->first();
                    if (!empty($feeinfo)) {
                        if ((int)$feeinfo['is_method'] == 1) {
                            $gv['commission1_cost_price_d'] = intval($feeinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_cost_price_d'] = intval($feeinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_cost_price_d'] = intval($feeinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_cost_price_d'] = intval($feeinfo['commission_money_2'] * $gv['weight']);
                        }

                    }
                    $gv['commission1_total'] = $gv['commission1_price_d'] + $gv['commission1_cost_price_d'] + $gv['commission1_cost_price'];
                    $gv['commission2_total'] = $gv['commission2_price_d'] + $gv['commission2_cost_price_d'] + $gv['commission2_cost_price'];

                } else {
                    //Discount
                    $discount = $gv['discount'] > 0 ? $gv['discount'] : 100;
                    $ruleinfo = Discount::where([['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['discount_min', '<=', $discount], ['discount_max', '>=', $discount], ['is_del', 1]])->first();
                    Log::info('ruleInfo:' . json_encode($ruleinfo));
                    Log::info('performance:' . $gv['performance']);
                    if ($ruleinfo) {
                        $gv['commission1_total'] = intval($ruleinfo['commission_rate_1'] * $gv['performance'] / 100);
                        $gv['commission2_total'] = intval($ruleinfo['commission_rate_2'] * $gv['performance'] / 100);
                    } else {
                        $gv['commission1_total'] = 0;
                        $gv['commission2_total'] = 0;
                    }
                    Log::info('commission1_total:' . $gv['commission1_total']);
                    Log::info('commission2_total:' . $gv['commission2_total']);

                    $gv['commission1_cost_price_d'] = 0;
                    $gv['commission2_cost_price_d'] = 0;
                    $gv['commission1_price_d'] = 0;
                    $gv['commission2_price_d'] = 0;
                    $gv['commission1_cost_price'] = 0;
                    $gv['commission2_cost_price'] = 0;
                }
                //提成

            }

            return compact('goodslist_new', 'recoverygoodslist_new', 'goods_moeny', 'recoverygoods_moeny');
        } else {
            //计算业绩
            //$recoverygoods_moeny=['su_money'=>0,'notsu_money'=>0];

            $recoverygoods_su_money = $recoverygoods_moeny['su_money'];
            $recoverygoods_notsu_money = $recoverygoods_moeny['notsu_money'];

            foreach ($goodslist_new as &$gv) {
                if ($gv['is_sujin'] == 1) {
                    if ($recoverygoods_moeny['su_money'] >= $gv['real_total_money_without_mian']) {
                        $gv['performance'] = 0;
                        $recoverygoods_moeny['su_money'] -= $gv['real_total_money_without_mian'];
                    } else {
                        if ($recoverygoods_moeny['su_money'] > 0) {
                            $gv['performance'] = $gv['real_total_money_without_mian'] - $recoverygoods_moeny['su_money'];
                            $recoverygoods_moeny['su_money'] = 0;
                        } else {
                            $gv['performance'] = $gv['real_total_money'];
                        }
                    }
                } else {
                    if ($recoverygoods_moeny['notsu_money'] >= $gv['real_total_money_without_mian']) {
                        $gv['performance'] = 0;
                        $recoverygoods_moeny['notsu_money'] -= $gv['real_total_money_without_mian'];

                    } else {
                        // echo $recoverygoods_moeny['notsu_money'];exit;
                        if ($recoverygoods_moeny['notsu_money'] > 0) {
                            $gv['performance'] = $gv['real_total_money_without_mian'] - $recoverygoods_moeny['notsu_money'];
                            $recoverygoods_moeny['notsu_money'] = 0;
                        } else {
                            $gv['performance'] = $gv['real_total_money'];
                        }
                    }
                }
            }
            $recoverygoods_moeny_total = $recoverygoods_moeny['su_money'] + $recoverygoods_moeny['notsu_money'];
            $sujinchange_type = ($recoverygoods_moeny['su_money'] > 0 || $recoverygoods_moeny['notsu_money'] > 0) ? ($recoverygoods_moeny['su_money'] > 0 ? 2 : 3) : 1;
            $is_open_added_recovery = SiteStore::where(['cp_id' => $goodslist_new[0]['cp_id'], 'id' => $goodslist_new[0]['store_id']])->value('is_open_added_recovery');

            foreach ($recoverygoodslist_new as &$rgv) {
                if ($sujinchange_type <= 1) {
                    $rgv['performance'] = 0;
                    $rgv['sujinchange_type'] = 1;
                    $rgv['recovery_type_price'] = 0;
                    continue;
                }

                if ($sujinchange_type == 2) { //剩余素
                    if ($rgv['is_sujin'] == 2) {
                        $rgv['performance'] = 0;
                        $rgv['sujinchange_type'] = 1;
                        $rgv['recovery_type_price'] = 0;
                        continue;
                    }
                    if ($recoverygoods_su_money > $recoverygoods_moeny['su_money']) {
                        $rgv['performance'] = 0;
                        $rgv['sujinchange_type'] = 1;

                        $rgv['recovery_type_price'] = 0;
                        $recoverygoods_su_money = $recoverygoods_su_money - $rgv['money'];

                        if ($recoverygoods_su_money < $recoverygoods_moeny['su_money']) {
                            $rgv['performance'] = ($recoverygoods_moeny['su_money'] - $recoverygoods_su_money);
                            $rgv['sujinchange_type'] = 2;
                        }
                        continue;
                    } else {
                        $rgv['sujinchange_type'] = 2;
                        $rgv['performance'] = $rgv['money'];

                    }
                } else { //剩余非素
                    if ($rgv['is_sujin'] == 1) {
                        $rgv['performance'] = 0;
                        $rgv['sujinchange_type'] = 1;

                        $rgv['recovery_type_price'] = 0;
                        continue;
                    }

                    if ($recoverygoods_notsu_money > $recoverygoods_moeny['notsu_money']) {
                        $rgv['performance'] = 0;
                        $rgv['sujinchange_type'] = 1;

                        $rgv['recovery_type_price'] = 0;

                        $recoverygoods_notsu_money = $recoverygoods_notsu_money - $rgv['money'];

                        if ($recoverygoods_notsu_money < $recoverygoods_moeny['notsu_money']) {
                            $rgv['performance'] = ($recoverygoods_moeny['notsu_money'] - $recoverygoods_notsu_money);
                            $rgv['sujinchange_type'] = 3;
                        }
                        continue;
                    } else {
                        $rgv['sujinchange_type'] = 3;
                        $rgv['performance'] = $rgv['money'];
                    }
                }


                if ($rgv['recovery_type'] == 1 && $rgv['sujinchange_type'] == 2) { //必须克换其他
                    if ($rgv['price'] > $rgv['sales_price']) {
                        $rgv['recovery_type_price'] = 1;
                    } else {
                        if ($rgv['price'] <= $rgv['old_recovery_price']) {
                            $rgv['recovery_type_price'] = 3;
                        } else {
                            $rgv['recovery_type_price'] = 2;
                        }
                    }
                    $rgv['performance'] = $rgv['money'];


                    if ($is_open_added_recovery == 2 && $rgv['recovery_type_price'] == 1) { //开启增值回收并且为增值回收
                        $rgv['performance'] = $rgv['performance'] - intval(($rgv['price'] - $rgv['old_recovery_price']) * (bcmul($rgv['count'], ($rgv['weight'] - $rgv['loss_weight']), 3)) * ($rgv['discount'] > 0 ? $rgv['discount'] : 100) / 100);
                    }
                } else {
                    $rgv['recovery_type_price'] = 0;
                }
            }


            foreach ($goodslist_new as &$gv) {
                if ($recoverygoods_moeny_total <= 0) {
                    break;
                }
                if ($gv['performance'] <= 0) {
                    continue;
                }
                if ($recoverygoods_moeny_total >= $gv['performance']) {
                    $gv['performance'] = 0;
                    $recoverygoods_moeny_total -= $gv['performance'];
                }
                // 业绩已经把非素的扣除了
//                else {
//                    if ($recoverygoods_moeny_total > 0) {
//                        $gv['performance'] = $gv['performance'] - $recoverygoods_moeny_total;
//                        $recoverygoods_moeny_total = 0;
//                    }
//                }
            }


            //换货旧料提成
            foreach ($recoverygoodslist_new as &$rgv) {
                if ($rgv['performance'] <= 0) {
                    $rgv['commission1'] = 0;
                    $rgv['commission2'] = 0;
                    continue;
                }
                //sujinchange_type==2,素换非，==3非换素
                //提成
                if ($rgv['sujinchange_type'] == 2) {
                    // 素换非 如果相同的数据取最新的
                    if ($rgv['recovery_type_price'] == 1) {
                        $ruleinfo = Changegoods::query()->where([['cp_id', $rgv['cp_id']], ['store_id', $rgv['store_id']], ['change_type', 2], ['change_channel', 2], ['discount_min', '<=', $rgv['discount']], ['discount_max', '>=', $rgv['discount']], ['is_del', 1]])->orderBy('id', 'desc')->first();
                    } else {
                        $ruleinfo = Changegoods::query()->where([['cp_id', $rgv['cp_id']], ['store_id', $rgv['store_id']], ['change_type', 2], ['change_channel', 1], ['discount_min', '<=', $rgv['discount']], ['discount_max', '>=', $rgv['discount']], ['is_del', 1]])->orderBy('id', 'desc')->first();
                    }
                } else {
                    $ruleinfo = Changegoods::where([['cp_id', $rgv['cp_id']], ['store_id', $rgv['store_id']], ['change_type', 1], ['discount_min', '<=', $rgv['discount']], ['discount_max', '>=', $rgv['discount']], ['is_del', 1]])->first();
                }

                if ($ruleinfo) {
                    $rgv['commission1'] = intval($ruleinfo['commission_rate_1'] * $rgv['performance'] / 100);
                    $rgv['commission2'] = intval($ruleinfo['commission_rate_2'] * $rgv['performance'] / 100);
                } else {
                    $rgv['commission1'] = 0;
                    $rgv['commission2'] = 0;
                }
            }

            foreach ($goodslist_new as &$gv) {

                if ($gv['performance'] <= 0) {
                    $gv['commission1_total'] = 0;
                    $gv['commission2_total'] = 0;
                    $gv['commission1_cost_price_d'] = 0;
                    $gv['commission2_cost_price_d'] = 0;
                    $gv['commission1_price_d'] = 0;
                    $gv['commission2_price_d'] = 0;
                    $gv['commission1_cost_price'] = 0;
                    $gv['commission2_cost_price'] = 0;
                    continue;
                }
                if ($gv['is_sujin'] == 1 && $gv['is_gram'] = 1) { //素金

                    $gv['commission1_price_d'] = 0;
                    $gv['commission2_price_d'] = 0;
                    $gv['commission1_cost_price_d'] = 0;
                    $gv['commission2_cost_price_d'] = 0;
                    $gv['commission1_cost_price'] = 0;
                    $gv['commission2_cost_price'] = 0;
                    // 金价优惠
                    $glodprice_total = $gv['glod_price_discount'] ?? -1;
                    //工费优惠
                    $fee_total = $gv['cost_price_discount'] ?? -1;
                    $preferential_total = $glodprice_total + $fee_total;

                    $ruleinfo = Priceandfee::where([
                        ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']],
                        ['preferential_min', '<=', $preferential_total], ['preferential_max', '>=', $preferential_total],
                        ['glodprice_min', '<=', $glodprice_total], ['glodprice_max', '>=', $glodprice_total],
                        ['fee_min', '<=', $fee_total], ['fee_max', '>=', $fee_total], ['is_del', 1]
                    ])->first();

                    if (!empty($ruleinfo)) {
                        if ((int)$ruleinfo['is_method'] == 1) {
                            $gv['commission1_cost_price'] = intval($ruleinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_cost_price'] = intval($ruleinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_cost_price'] = intval($ruleinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_cost_price'] = intval($ruleinfo['commission_money_2'] * $gv['weight']);
                        }
                    }

                    $glodpriceinfo = Preferention::where([['type', 1], ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['preferential_min', '<=', $glodprice_total], ['preferential_max', '>=', $glodprice_total], ['is_del', 1]])->first();
                    if (!empty($glodpriceinfo)) {
                        if ((int)$glodpriceinfo['is_method'] == 1) {
                            $gv['commission1_price_d'] = intval($glodpriceinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_price_d'] = intval($glodpriceinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_price_d'] = intval($glodpriceinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_price_d'] = intval($glodpriceinfo['commission_money_2'] * $gv['weight']);
                        }

                    }

                    $feeinfo = Preferention::where([['type', 2], ['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['preferential_min', '<=', $fee_total], ['preferential_max', '>=', $fee_total], ['is_del', 1]])->first();
                    if (!empty($feeinfo)) {
                        if ((int)$feeinfo['is_method'] == 1) {
                            $gv['commission1_cost_price_d'] = intval($feeinfo['commission_rate_1'] * $gv['performance'] / 100);
                            $gv['commission2_cost_price_d'] = intval($feeinfo['commission_rate_2'] * $gv['performance'] / 100);
                        } else {
                            $gv['commission1_cost_price_d'] = intval($feeinfo['commission_money_1'] * $gv['weight']);
                            $gv['commission2_cost_price_d'] = intval($feeinfo['commission_money_2'] * $gv['weight']);
                        }

                    }


                    $gv['commission1_total'] = $gv['commission1_price_d'] + $gv['commission1_cost_price_d'] + $gv['commission1_cost_price'];
                    $gv['commission2_total'] = $gv['commission2_price_d'] + $gv['commission2_cost_price_d'] + $gv['commission2_cost_price'];
                } else {
                    // 非素
                    $discount = $gv['discount'] > 0 ? $gv['discount'] : 100;

                    $ruleinfo = Discount::query()->where([['goods_category_id', $gv['goods_category_id']], ['cp_id', $gv['cp_id']], ['store_id', $gv['store_id']], ['discount_min', '<=', $discount], ['discount_max', '>=', $discount], ['is_del', 1]])->first();
                    //print_r($ruleinfo);exit;
                    if ($ruleinfo) {
                        $gv['commission1_total'] = intval($ruleinfo['commission_rate_1'] * $gv['performance'] / 100);
                        $gv['commission2_total'] = intval($ruleinfo['commission_rate_2'] * $gv['performance'] / 100);
                    } else {
                        $gv['commission1_total'] = 0;
                        $gv['commission2_total'] = 0;
                    }

                    $gv['commission1_cost_price_d'] = 0;
                    $gv['commission2_cost_price_d'] = 0;
                    $gv['commission1_price_d'] = 0;
                    $gv['commission2_price_d'] = 0;
                    $gv['commission1_cost_price'] = 0;
                    $gv['commission2_cost_price'] = 0;
                }
                //提成
            }


            return compact('goodslist_new', 'recoverygoodslist_new', 'goods_moeny', 'recoverygoods_moeny');
        }
    }

    /**
     *  销售订单数据打印
     * @param $orderid
     * @param $request
     * @param $isPrint
     * @return array
     */
    public static function getOrderPrintData($orderid, $request, $isPrint = false)
    {

        if ($isPrint == false) {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        } else {
            $accountinfo = Account::query()
                ->where('id', $request->account_id)
                ->first();
            $accountinfo = empty($accountinfo) ? [] : $accountinfo->toArray();
        }

        $print_temp_id = $request->print_temp_id ?? 0;

        $withinfo = [
            'memberinfo',
            'shoppingaccountinfo1',
            'shoppingaccountinfo2',
            'storeinfo',
            'goodslist',
            'recoverygoodslist',
            'paytypeinfo',
            'sendgoodslist',
            'companyinfo',
            // 'classessetinfo'
        ];
        $info = ModelsOrderOrderSales::with($withinfo)
            ->where(['id' => $orderid, 'is_del' => 1])->first();

        if ($info) {
            $info = $info->toArray();


            $goodsdata = [];
            $cost_price_total = 0;//克销工费总额
            $count_total = 0;//总数量
            $weight_total = 0;//总金重
            foreach ($info['goodslist'] as $k => $v) {
                $goodsinfo = json_decode($v['goodsinfo'], true);
                $goodsdata[] = [
                    'goods_sn_code' => $v['goods_sn_code'],
                    'goods_name' => $v['goods_name'],
                    'piece_weight' => $goodsinfo['goods_category']['is_gram'] == 1 ? '' : $v['weight'] / $v['count'],
                    'label_price' => $v['label_price'] / 100,
                    'cost_price' => empty($v['cost_price']) ? '' : $v['cost_price'] / 100,
                    'pieceprice_fee' => empty($v['pieceprice_fee']) ? '' : $v['pieceprice_fee'] / 100,
                    'labor_cost_total' => ((($v['cost_price'] - $v['cost_price_discount']) * $v['weight']) + ($v['pieceprice_fee'] * $v['count'])) / 100,
                    'gold_weight1' => $v['weight'],
                    'gold_weight2' => $v['weight'],
                    'gold_weight3' => $goodsinfo['goods_category']['is_gram'] == 2 ? '' : $v['weight'],
                    'gold_weight4' => $goodsinfo['goods_category']['is_gram'] == 2 ? '' : $v['weight'],
                    'add_fee1' => $v['add_fee1'] / 100,
                    'add_fee2' => $v['add_fee2'] / 100,
                    'gemstone_fee1' => $v['gemstone_fee1'] / 100,
                    'gemstone_fee2' => $v['gemstone_fee2'] / 100,
                    'costglod_price' => $v['costglod_price'] / 100,
                    'costglod_price2' => $v['costglod_price'] / 100,
                    'discount_money' => $v['discount_money'] / 100,
                    'real_total_money' => $v['money_received'] > 0 ? ($v['money_received'] / 100) : ($v['real_total_money'] / 100),
                    'capital_real_total_money' => $v['money_received'] > 0 ? self::num_to_rmb($v['money_received'] / 100) : self::num_to_rmb($v['real_total_money'] / 100),
                    'style_name' => empty($goodsinfo['goods_style']) ? '' : $goodsinfo['goods_style']['style_name'],
                    's_no' => $goodsinfo['s_no'],
                    'content' => $goodsinfo['goods_content']['content_name'] ?? '',
                    'count' => $v['count'],
                    'craft_name' => $goodsinfo['goods_craft']['craft_name'] ?? '',
                    'c_no' => $goodsinfo['c_no'],
                    'brand_name' => $goodsinfo['goods_brand']['brand_name'] ?? '',
                    'cf_no' => $goodsinfo['cf_no'],
                    'cf_no_gia' => $goodsinfo['cf_no_gia'],
                    'main_stone_weigth' => $goodsinfo['main_stone_weigth'],
                    'other_stone_weigth' => $goodsinfo['other_stone_weigth'],
                    'main_stone_count' => $goodsinfo['main_stone_count'],
                    'other_stone_count' => $goodsinfo['other_stone_count'],
                    'color' => $goodsinfo['color'],
                    'clarity' => $goodsinfo['clarity'],
                    'cut' => $goodsinfo['cut'],
                    'pricetype_name' => $goodsinfo['goods_pricetype']['pricetype_name'] ?? '',
                    'remark' => $v['remark'],
                    'discount' => $v['discount'],
                    'cost_price_discount' => $v['cost_price_discount'] / 100,
                    'glod_price_discount' => $v['glod_price_discount'] / 100,
                    'category_name' => $goodsinfo['goods_category']['category_name'] ?? '',
                    'dold_price' => '',
                    'dold_fee' => '',
                    'loss_weight' => '',
                    'truncate_glod_weight' => $v['truncate_glod_weight'],
                    'truncate_glod_money' => $v['truncate_glod_money'] / 100,
                    'total_money' => $v['total_money'] / 100,
                    'old_catefory_name' => '',
                    'recovery_weight' => '',
                    'recovery_price' => '',
                    'recovery_d_price' => '',
                    'recovery_money' => '',
                    'sendgoods_name' => '',
                    'recovery_type' => '',
                    'change_type' => '',
                ];
                $cost_price_total += empty($v['cost_price']) ? 0 : $v['cost_price'] / 100;
                $count_total += $v['count'];
                $weight_total += $v['weight'];
            }

            $recoveryData = [];
            // 回收商品
            if (is_array($info['recoverygoodslist']) && count($info['recoverygoodslist']) > 0) {
                foreach ($info['recoverygoodslist'] as $k => $v) {
                    $goods_sn_code = empty($v['goods_sn_code']) ? '旧料' : ('旧料:' . $v['goods_sn_code']);
                    $recoveryData[] = [
                        'goods_sn_code' => $goods_sn_code,
                        'goods_name' => $v['goods_catefory_name'] ?? '',
                        'piece_weight' => $v['weight'],//'按件回收的重量'
                        'label_price' => $v['d_price'] / 100,
                        'cost_price' => '',
                        'pieceprice_fee' => '',
                        'gold_weight1' => $v['weight'],//'按件按克回收重量'
                        'gold_weight2' => '',
                        'gold_weight3' => ($v['recovery_type'] == 1) ? $v['weight'] : '',//旧料按克回收的回收重量
                        'gold_weight4' => $v['weight'], //-旧料回收按克按件的回收重量
                        'add_fee1' => '',
                        'add_fee2' => '',
                        'gemstone_fee1' => '',
                        'gemstone_fee2' => '',
                        'costglod_price' => '',
                        'costglod_price2' => $v['price'] / 100,
                        'discount_money' => '',
                        'real_total_money' => -$v['money'] / 100,//'开单-回收金额（负数显示）'
                        'capital_real_total_money' => '',
                        'style_name' => '',
                        's_no' => '',
                        'content' => '',
                        'count' => $v['count'],//'旧料的数量'
                        'craft_name' => '',
                        'c_no' => '',
                        'brand_name' => '',
                        'cf_no' => '',
                        'cf_no_gia' => '',
                        'main_stone_weigth' => '',
                        'other_stone_weigth' => '',
                        'main_stone_count' => '',
                        'other_stone_count' => '',
                        'color' => '',
                        'clarity' => '',
                        'cut' => '',
                        'pricetype_name' => '',
                        'remark' => '',
                        'discount' => $v['discount'],//'旧料的折扣'
                        'cost_price_discount' => '',
                        'glod_price_discount' => '',
                        'category_name' => $v['goods_catefory_name'],//'旧料品类'
                        'dold_price' => $v['dold_price'] / 100,//'单个旧料的折旧单价'
                        'dold_fee' => $v['dold_fee'] / 100,//'单个旧料的折旧工费'
                        'loss_weight' => $v['loss_weight'],//'单个旧料的损耗重量'
                        'truncate_glod_weight' => '',
                        'truncate_glod_money' => '',
                        'total_money' => '',
                        'old_catefory_name' => $v['goods_catefory_name'],//'旧料品类'
                        'recovery_weight' => $v['weight'],
                        'recovery_price' => $v['price'] / 100,
                        'recovery_d_price' => $v['d_price'] / 100,//'回收标价'
                        'recovery_money' => $v['money'] / 100,//'回收金额',
                        'sendgoods_name' => '',
                        'recovery_type' => $v['recovery_type'] == 1 ? '按克' : '标价',
                        'change_type' => $v['change_type'] == 1 ? '回收' : '上柜',
                    ];
                }

            }

            $sendData = [];

            if (is_array($info['sendgoodslist']) && count($info['sendgoodslist']) > 0) {
                foreach ($info['sendgoodslist'] as $k => $v) {
                    $sendData[] = [
                        'goods_sn_code' => '赠品',
                        'goods_name' => $v['sendgoods_name'] ?? '',//赠品库存-赠品名称
                        'piece_weight' => '',
                        'label_price' => '',
                        'cost_price' => '',
                        'pieceprice_fee' => '',
                        'gold_weight1' => '',
                        'gold_weight2' => '',
                        'gold_weight3' => '',
                        'gold_weight4' => '',
                        'add_fee1' => '',
                        'add_fee2' => '',
                        'gemstone_fee1' => '',
                        'gemstone_fee2' => '',
                        'costglod_price' => '',
                        'costglod_price2' => '',
                        'discount_money' => '',
                        'real_total_money' => '',
                        'capital_real_total_money' => '',
                        'style_name' => '',
                        's_no' => '',
                        'content' => '',
                        'count' => $v['count'] ?? 0,
                        'craft_name' => '',
                        'c_no' => '',
                        'brand_name' => '',
                        'cf_no' => '',
                        'cf_no_gia' => '',
                        'main_stone_weigth' => '',
                        'other_stone_weigth' => '',
                        'main_stone_count' => '',
                        'other_stone_count' => '',
                        'color' => '',
                        'clarity' => '',
                        'cut' => '',
                        'pricetype_name' => '',
                        'remark' => '',
                        'discount' => '',
                        'cost_price_discount' => '',
                        'glod_price_discount' => '',
                        'category_name' => '',
                        'dold_price' => '',
                        'dold_fee' => '',
                        'loss_weight' => '',
                        'truncate_glod_weight' => '',
                        'truncate_glod_money' => '',
                        'total_money' => '',
                        'old_catefory_name' => '',
                        'recovery_weight' => '',
                        'recovery_price' => '',
                        'recovery_d_price' => '',
                        'recovery_money' => '',
                        'sendgoods_name' => empty($v['sendgoods_name']) && empty($v['count']) ? ($v['sendgoods_name'] . $v['count']) : '',
                        'recovery_type' => '',
                        'change_type' => '',
                    ];
                }

            }


            if ($info['pay_type_id'] == -1) {
                $paytype_name = '';
                //                {"paytype_16":140000,"paytype_9":5600,"paytype_7":200000}
                foreach ($info['mixed_payment'] as $k => $va) {
                    $paytype_id = substr($k, 8);
                    $va = $va / 100;
                    $paytype_name .= PaytypeList::where('id', '=', $paytype_id)->value('paytype_name') . ":" . $va . ' ';
                };
            } else {
                $paytype_name = $info['paytypeinfo']['paytype_name'] ?? '';
            }
            $allinfo = [
                'cost_price_total' => $cost_price_total,
                'real_money_total' => $info['real_money'] / 100,
                'capital_real_money_total' => $info['pay_money'] > 0 ? self::num_to_rmb($info['pay_money'] / 100) : '负' . self::num_to_rmb(abs($info['pay_money']) / 100),
                'paytype_name' => $paytype_name,
                'order_sn' => $info['order_sn'],
                'real_name' => $accountinfo['real_name'],
                'store_name' => $info['storeinfo']['store_name'] ?? '',
                'address_area' => $info['storeinfo']['address_area'] ?? '',
                'contact_phone' => $info['storeinfo']['contact_phone'] ?? '',
                'count_total' => $count_total,
                'weight_total' => $weight_total,
                'remark' => $info['remark'],
                'total_discounts' => $info['discount_moeny'] > 0 ? (($info['discount_moeny']) / 100) : 0,
                'shop_account' => $info['shoppingaccountinfo1']['real_name'],
                'assistant_shop_account' => $info['shoppingaccountinfo2'] ? $info['shoppingaccountinfo2']['real_name'] : '',
                'changegoods_money' => $info['changegoods_money'] / 100,
                'round_down_money' => $info['round_down_money'] / 100,
                'order_discount' => $info['order_discount'],
                'total_money' => $info['pay_money'] / 100,
                'coupon_money' => $info['coupon_money'] / 100,
                'mem_real_name' => $info['memberinfo'] ? $info['memberinfo']['real_name'] : '',
                'mem_mobile' => $info['memberinfo'] ? $info['memberinfo']['mobile'] : '',
                'mem_points' => ($info['issendpoints'] == 2 && $info['mem_id'] > 0) ? $info['order_points'] + $info['order_points_recovery'] + $info['share_mem_send_points'] : '',
                'mem_points_current' => $info['memberinfo'] ? $info['memberinfo']['points_current'] : '',
                'mem_lunar_bdate' => $info['memberinfo'] ? $info['memberinfo']['lunar_bdate'] : '',
                'mem_solar_bdate' => $info['memberinfo'] ? $info['memberinfo']['solar_bdate'] : '',
                'mem_card_no' => $info['memberinfo'] ? $info['memberinfo']['mem_card_no'] : '',
                'mem_pre_money' => $info['memberinfo'] ? $info['memberinfo']['pre_money'] / 100 : '',
                'balance_money' => (($info['balance_money'] ?? 0) + ($info['pointstobalance'] ?? 0)) / 100,
                'pre_money' => $info['memberinfo'] ? $info['memberinfo']['pre_money'] / 100 : '',
                'order_time' => date('Y-m-d H:i:s', $info['order_at']),
                'print_time' => date('Y-m-d H:i:s'),
                'order_type' => '销售开单',
            ];

            //此处需要区分打印模板类型
            $temp = TemplateQuality::query()
                ->where('id', $print_temp_id)
                ->where('cp_id', $accountinfo['cp_id'])
                ->first();

            $goodsAll = array_values(array_merge($goodsdata, $recoveryData, $sendData));

            if (!empty($temp)) {
                $temp = $temp->toArray();
                if ($temp['type'] == 4) {
                    $goodsAll = array_values(array_merge($goodsdata, $sendData));
                } elseif ($temp['type'] == 5) {
                    $goodsAll = array_values(array_merge($recoveryData));
                }
            }

            return ['info' => $allinfo, 'goodsdata' => $goodsAll];
        } else {
            return [];
        }


    }


    public static function num_to_rmb($num)
    {

        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }

        $i = 0;
        $c = "";

        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }

            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);

            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }

        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {

            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }

        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }

        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";

        }

    }
}
